﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace eWallet.Security.Cryptography
{
	[Serializable]
	internal struct SymmetricAlgorithmInfo
	{

		public SymmetricAlgorithmInfo(SymmetricAlgorithm algorithm)
			: this()
		{
			if (null == algorithm)
				throw new ArgumentNullException("algorithm");

			this.AlgorithmName = GetAlgorithmName(algorithm.GetType());
			if (string.IsNullOrEmpty(this.AlgorithmName))
				throw new ArgumentException("Cannot resolve the name for the given algorithm.", "algorithm");

			this.IV = algorithm.IV;
			this.Key = algorithm.Key;
		}

		public string AlgorithmName { get; set; }
		public byte[] IV { get; set; }
		public byte[] Key { get; set; }

		public SymmetricAlgorithm CreateAlgorithm()
		{
			var algo = SymmetricAlgorithm.Create(this.AlgorithmName);
			algo.IV = this.IV;
			algo.Key = this.Key;
			return algo;
		}



		private static string GetAlgorithmName(Type algorithmType)
		{
			string name = algorithmType.Name;
			SymmetricAlgorithm algo = null;
			try
			{
				algo = SymmetricAlgorithm.Create(name);
			}
			catch { }

			if (null == algo && null != algorithmType.BaseType)
			{
				return GetAlgorithmName(algorithmType.BaseType);
			}

			if (null != algo)
				return name;

			return null;
		}
	}
}
